package com.ssy.lingxi.search.serviceImpl;

import cn.hutool.core.date.DateUtil;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberLevelRightCreditControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignLevelDetailVO;
import com.ssy.lingxi.search.api.model.request.SimpleIdListRequest;
import com.ssy.lingxi.search.entity.BrowseRecord;
import com.ssy.lingxi.search.entity.Commodity;
import com.ssy.lingxi.search.entity.CommodityShop;
import com.ssy.lingxi.search.entity.CommoditySoldCount;
import com.ssy.lingxi.search.model.response.BrowseRecordResponse;
import com.ssy.lingxi.search.repository.BrowseRecordRepository;
import com.ssy.lingxi.search.repository.CommodityRepository;
import com.ssy.lingxi.search.service.IBrowseRecordService;
import com.ssy.lingxi.search.service.ICommodityService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 浏览记录实现类
 * @author jw.chen
 * @version 2.0.0
 * @date 2020/6/22
 */
@Service
public class BrowseRecordServiceImpl implements IBrowseRecordService {

    @Resource
    private BrowseRecordRepository browseRecordRepository;

    @Resource
    private CommodityRepository commodityRepository;

    @Resource
    private ICommodityService commodityService;

    @Resource
    private MemberLevelRightCreditControllerFeign memberLevelRightCreditControllerFeign;

    /**
     * 查询浏览记录列表
     */
    @Override
    public PageData<BrowseRecordResponse> getBrowseRecordList(UserLoginCacheDTO sysUser, Long shopId, int current, int pageSize){
        //查询浏览记录
        List<BrowseRecordResponse> browseRecordResponseList = new ArrayList<>();
        Long memberId = sysUser.getMemberId();
        Long memberRoleId = sysUser.getMemberRoleId();
        Long userId = sysUser.getUserId();

        Pageable page = PageRequest.of(current - 1, pageSize, Sort.by("createTime").descending());
        Page<BrowseRecord> browseRecordPage = browseRecordRepository.findByMemberIdAndMemberRoleIdAndUserIdAndShopId(memberId, memberRoleId, userId, shopId, page);
        List<BrowseRecord> browseRecordList = browseRecordPage.getContent();
        if(!browseRecordList.isEmpty()){
            Map<Long, Commodity> commodityMap = new HashMap<>();
            List<Long> commodityIdList = browseRecordList.stream().map(BrowseRecord::getCommodityId).collect(Collectors.toList());
            List<Commodity> commodityList = commodityRepository.findByIdIn(commodityIdList);
            if(commodityList != null && commodityList.size() > 0) {
                commodityMap = commodityList.stream().collect(Collectors.toMap(Commodity::getId, Commodity -> Commodity));
            }

            //查询登录用户的所有上级对应的会员等级
            Map<String, Integer> memberLevelMap = new HashMap<>();
            MemberFeignVO memberFeignVO = new MemberFeignVO();
            memberFeignVO.setMemberId(memberId);
            memberFeignVO.setRoleId(memberRoleId);
            Wrapper<List<MemberFeignLevelDetailVO>> subMemberLevels = memberLevelRightCreditControllerFeign.findSubMemberLevels(memberFeignVO);
            if(subMemberLevels != null && ResponseCode.SUCCESS.getCode() == subMemberLevels.getCode()){
                List<MemberFeignLevelDetailVO> data = subMemberLevels.getData();
                if(!CollectionUtils.isEmpty(data)){
                    data.stream().filter(memberFeignLevelDetailVO -> memberFeignLevelDetailVO.getRelType() == 1).forEach(memberFeignLevelDetailVO -> {
                        Long upperMemberId = memberFeignLevelDetailVO.getUpperMemberId();
                        Long upperRoleId = memberFeignLevelDetailVO.getUpperRoleId();
                        Integer level = memberFeignLevelDetailVO.getLevel();
                        memberLevelMap.put(upperMemberId + Constants.UNDERLINE_STR + upperRoleId, level);
                    });
                }
            }

            for(BrowseRecord browseRecord : browseRecordList){
                Long commodityId = browseRecord.getCommodityId();
                BrowseRecordResponse browseRecordResponse = new BrowseRecordResponse();
                browseRecordResponse.setId(browseRecord.getId());
                browseRecordResponse.setCommodityId(browseRecord.getCommodityId());
                browseRecordResponse.setCreateTime(browseRecord.getCreateTime());

                Commodity commodity = commodityMap.get(commodityId);
                if(commodity != null){
                    Integer memberLevel = memberLevelMap.get(commodity.getMemberId() + Constants.UNDERLINE_STR + commodity.getMemberRoleId());
                    //获取价格策略的价格
                    commodityService.setCommodityPrice(commodity, shopId, memberId, memberRoleId, memberLevel == null ? 0 : memberLevel);
                    //不同商城显示不同的已售数量
                    List<CommoditySoldCount> commoditySoldCountList = commodity.getCommoditySoldCountList();
                    if(commoditySoldCountList != null && commoditySoldCountList.size() > 0){
                        commoditySoldCountList.forEach(commoditySoldCount -> {
                            Long commoditySoldCountShopId = commoditySoldCount.getShopId();
                            double sold = commoditySoldCount.getSold();
                            if(commoditySoldCountShopId.equals(shopId)){
                                browseRecordResponse.setSold(sold);
                            }
                        });
                    }
                    //是否上架
                    List<CommodityShop> commodityShopList = commodity.getCommodityShopList();
                    if(commodityShopList != null && commodityShopList.size() > 0){
                        boolean isPublish = commodityShopList.stream().anyMatch(commodityShop -> commodityShop.getShopId().equals(shopId));
                        browseRecordResponse.setIsPublish(isPublish);
                    }
                    browseRecordResponse.setCommodityName(commodity.getName());
                    browseRecordResponse.setMainPic(commodity.getMainPic());
                    browseRecordResponse.setUnitName(commodity.getUnitName());
                    browseRecordResponse.setMax(commodity.getMax());
                    browseRecordResponse.setMin(commodity.getMin());
                }else{
                    browseRecordResponse.setCommodityName("");
                }
                browseRecordResponseList.add(browseRecordResponse);
            }
        }
        return new PageData<>(browseRecordPage.getTotalElements(), browseRecordResponseList);
    }

    /**
     * 添加浏览记录
     * @param shopId
     * @param commodityId
     * @return
     */
    @Override
    public void saveBrowseRecord(UserLoginCacheDTO sysUser, Long shopId, Long commodityId){
        BrowseRecord oldBrowseRecord = browseRecordRepository.findFirstByMemberIdAndMemberRoleIdAndUserIdAndShopIdAndCommodityIdOrderByCreateTimeDesc(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, commodityId);
        if(oldBrowseRecord != null){
            //同一天的同一个商品只记录最后一次
            Long createTime = oldBrowseRecord.getCreateTime();
            boolean sameDay = DateUtil.isSameDay(new Date(), new Date(createTime));
            if(sameDay){
                oldBrowseRecord.setCreateTime(System.currentTimeMillis());
                browseRecordRepository.saveAndFlush(oldBrowseRecord);
            }else {
                BrowseRecord browseRecord = this.setBrowseRecord(sysUser, shopId, commodityId);
                browseRecordRepository.saveAndFlush(browseRecord);
            }
        }else{
            BrowseRecord browseRecord = this.setBrowseRecord(sysUser, shopId, commodityId);
            browseRecordRepository.saveAndFlush(browseRecord);
        }
    }

    /**
     * 删除浏览记录
     * @param sysUser
     * @param shopId
     * @param simpleIdListRequest
     * @return
     */
    @Override
    public Boolean deleteBrowseRecord(UserLoginCacheDTO sysUser, Long shopId, SimpleIdListRequest simpleIdListRequest) {
        int size = browseRecordRepository.deleteByMemberIdAndMemberRoleIdAndUserIdAndShopIdAndIdIn(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId, simpleIdListRequest.getIdList());
        return size > 0;
    }

    /**
     * 清空浏览记录
     * @param sysUser
     * @param shopId
     * @return
     */
    @Override
    public Boolean clearBrowseRecord(UserLoginCacheDTO sysUser, Long shopId) {
        int size = browseRecordRepository.deleteByMemberIdAndMemberRoleIdAndUserIdAndShopId(sysUser.getMemberId(), sysUser.getMemberRoleId(), sysUser.getUserId(), shopId);
        return size > 0;
    }

    /**
     * 实例化浏览记录对象
     * @param sysUser
     * @param shopId
     * @param commodityId
     * @return
     */
    private BrowseRecord setBrowseRecord(UserLoginCacheDTO sysUser, Long shopId, Long commodityId){
        BrowseRecord browseRecord = new BrowseRecord();
        browseRecord.setShopId(shopId);
        browseRecord.setCommodityId(commodityId);
        browseRecord.setCreateTime(System.currentTimeMillis());
        browseRecord.setMemberId(sysUser.getMemberId());
        browseRecord.setMemberName(sysUser.getCompany());
        browseRecord.setMemberRoleId(sysUser.getMemberRoleId());
        browseRecord.setMemberRoleName(sysUser.getMemberRoleName());
        browseRecord.setUserId(sysUser.getUserId());
        browseRecord.setUserName(sysUser.getUserName());
        return browseRecord;
    }

}

